package com.hzyc.springdata.jpa.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.querydsl.QPageRequest;
import org.springframework.stereotype.Service;

import com.hzyc.springdata.jpa.dao.UserJpaRepository;
import com.hzyc.springdata.jpa.domain.User;
import com.hzyc.springdata.jpa.service.IUserService;

@Service
public class UserServiceImpl implements IUserService {

	@Resource
	private UserJpaRepository userJpaRepository;

	@Override
	public boolean addUser(User user) {
		long id = userJpaRepository.save(user).getId();
		return id > 0;
	}

	@Override
	public User get(long id) {
		return userJpaRepository.findOne(id);
	}

	public Page<User> getByPage(int page, int size) {
		Sort sort = new Sort(new Sort.Order(Sort.Direction.ASC, "userName"));
		return userJpaRepository.findAll(new PageRequest(page, size, sort));
	}

	@Override
	public List<User> findByUserNameAndPassword(String userName, String password) {
		return userJpaRepository.findByUserNameAndPassWord(userName, password);
	}

	@Override
	public List<User> findByRoleOrderByIdDesc(String role) {
		return null;
	}

	@Override
	public Long countByUserName(String name) {
		return userJpaRepository.countByUserName(name);
	}

	public Page<User> findByRole(String role, int page, int size) {
		Pageable pageable = new QPageRequest(page, size);
		return userJpaRepository.findByRole(role, pageable);
	}

	public List<User> findByRole(String role) {
		Sort sort = new Sort(new Sort.Order(Sort.Direction.DESC, "id"));
		return userJpaRepository.findByRole(role, sort);
	}

	public List<User> queryUser(String userName) {
		return userJpaRepository.queryUser(userName);
	}

	public User login(String userName, String password) {
		return userJpaRepository.login(userName, password);
	}

	public int setUserNameById(String userName, int id) {
		return userJpaRepository.setUserNameById(userName, id);
	}

	public static class A {

	}

	public class B {

	}
}
